import React, { Component } from 'react';
import { connect } from 'react-redux';
import { messages } from 'share/common';
import config from 'config';
import { Input, Button, Icon, message, Modal } from 'antd';
import ReconnectingWebSocket from "reconnectingwebsocket";
import menuRoute from 'routes/menuRoute';
import Condition from 'components/condition'
import WaterMark from 'components/water-mark';
import bagService from "../invoice-bag-approve.service";
import 'styles/financial-management/scan-send-wrap.scss';
import { getWsUrl } from 'share/utils';

const { If } = Condition;

class ScanGunAuditBag extends Component {
  state = {
    identifying: false,
    inputValue: '',
    hasConfirm: false,
  };

  data = [];

  componentDidMount() {
    this.focusInput();
  }

  componentWillMount() {
    this.connector && this.connector.close();
    !window.ISIE9 && this.openWebSocket();
  }

  componentWillUnmount = () => {
    this.connector && this.connector.close();
  };

  //webSocket扫码审核开始
  openWebSocket = () => {
    let url = getWsUrl('/ws/scancode?scanMode=BAG_REVIEW');
    this.connector = new ReconnectingWebSocket(url);
    this.connector.onopen = this.onOpen;
    this.connector.onerror = this.onError;
    this.connector.onmessage = this.onMessage;
    this.connector.onclose = this.onClose;
  };

  onOpen = () => {
    let body = {
      userOID: this.props.user.userOID,
      token: this.props.authToken.access_token
    };
    let dict = {
      command: 'AUTH',
      body: JSON.stringify(body)
    };
    let dataSend = JSON.stringify(dict) + '\0';
    this.connector.send(dataSend);
  };

  onError = () => {
    this.setState({ connectStatus: false })
  };

  onMessage = (message) => {
    this.data.push(JSON.parse(JSON.stringify(message)).data);
    this.analyseData();
  };

  onClose = () => {
    if (this.state.connectStatus)
      this.setState({connectStatus: false});
  };

  analyseData = () => {
    let lastReceive = this.data.pop();
    let end = '\0';
    if (lastReceive.indexOf(end) === -1) {
      this.data.push(lastReceive);
      return;
    }
    let temp = lastReceive.split(end);
    let data = JSON.parse(this.data.join('') + temp[0]);
    if (temp[1] !== '') {
      this.data = [];
      this.data.push(temp[1]);
    }
    if (data.command === 'ERROR') {
      if (this.state.hasConfirm)
        return;
      this.setState({hasConfirm: true});
      Modal.confirm({
        title: 'Oops',
        content: data.body,
        okText: messages('expense-15.key19')/*重连*/,
        cancelText: messages('common.cancel')/*取消*/,
        onOk: () => {
          this.setState({hasConfirm: false});
        },
        onCancel: () => {
          this.setState({hasConfirm: false});
          this.data = [];
          this.connector.close();
        }
      })
    }
    data.body = data.command === 'MESSAGE' ? JSON.parse(data.body) : '';
    if (!data.body || !data.body.type || !data.body.content) return;
    if (data.command !== 'MESSAGE') return;
    let content = data.body.content.split(':');
    if (data.body.type === 'AUTH_SUCCESS') {
      this.setState({ connectStatus: true });
    } else if(data.body.type === 'BAG_REVIEW') {
      this.context.router.push(this.detailPage.url.replace(':id', content[0]) + `?tab=wait-for-approve`);
    }
  };

  focusInput = () => {
    setTimeout(() => {
      this.input.focus();
    }, 300);
  };

  handlePressEnter = e => {
    let params = {
      code: e.target.value,
      operate: 'BAG_REVIEW'
    };
    this.setState({ identifying: true });
    bagService.scanInvoiceBag(params)
      .then(res => {
        if (res.data.success && res.data.id) {
          const url = menuRoute.getRouteItem('invoice-bag-approve-detail').url
            .replace(':id', res.data.id) + '?backType=history';
          this.context.router.push(url);
        } else {
          message.error(res.data.message ||
            messages('expense-15.key20')/*员工未在系统中添加该发票袋*/
          )
        }
      })
      .finally(() => {
        this.setState({
          identifying: false,
          inputValue: ''
        });
        this.input.focus();
      })
  };

  handleClickSwitch = () => {
    this.context.router.push(menuRoute.getRouteItem('invoice-bag-approve').url);
  };

  render() {
    const { identifying, inputValue } = this.state;
    return (
      <div style={{position: 'absolute', minHeight: 'calc(100% - 100px)', width: 'calc(100% - 40px)'}}>
        <WaterMark />
        <div className="scan-send-wrap">
          <div className="scan-send-header">
            <Button type="primary" icon="layout" className="btn-change"
                    onClick={this.handleClickSwitch}>
              {messages('expense-15.key21')/*普通审核*/}
            </Button>
            <h1>{messages('expense-15.key1')/*扫码枪审核*/}</h1>
          </div>
          <div style={{ position: 'relative' }}>
            <Input
              value={inputValue}
              onChange={e=> this.setState({inputValue: e.target.value})}
              onPressEnter={this.handlePressEnter}
              ref={input => this.input = input}
              className="input-search"
              disabled={identifying}
            />
            <p style={{ color: '#8B93A7', marginTop: 8 }}>
              {messages('expense-15.key22')/*若您扫码后提示单据不存在，或无法跳转至单据详情页，请尝试：1. 输入法切换至英文环境后再扫码；2. 确认您的扫码枪已设置回车后缀*/}
            </p>
            <If value={identifying}>
              <Icon type="loading" style={{ position: 'absolute', top: '6px', right: '8px', zIndex: 1 }}/>
            </If>
          </div>
        </div>
      </div>
    );
  }
}

ScanGunAuditBag.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    authToken: state.main.authToken
  }
}

export default connect(mapStateToProps)(ScanGunAuditBag);
